#include"Sock.hpp"
#include<fstream>
#include <sys/stat.h>


#define WWWROOT "./wwwhtml/"
#define PAGE "index.html"//网站首页

void *HandlerRequest(void *args)
{
    int sock = *(int *)args;
    delete (int *)args;
    pthread_detach(pthread_self());
    
    //1.读取请求
    char buffer[1024*10];
    memset(buffer, 0, sizeof(buffer));
    ssize_t s = recv(sock, buffer, sizeof(buffer)-1, 0);
    if(s > 0)
    {
        buffer[s] = 0;
        cout << buffer;

        // string response_str = "http/1.1 307 Temporary Redirect\n";
        // response_str += "Content-Type: text/plain\n"; //text/plain,正文是普通的文本
        // //response_str += "Location: https://www.csdn.net/\n";
        // response_str += "\n"; //空行
        // response_str += "hello yzy !!!!";//正文

        //响应
        //读取index.html文件
        string html_file = WWWROOT;
        html_file += PAGE;

        struct stat st;
        stat(html_file.c_str(), &st);//stat 接口，通过指定的路径获取文件的属性，第二个参数是一个结构体，是一个输出型参数
        // 返回的时候，不仅仅是返回正文网页信息，而是还要包括http的请求
        std::string http_response = "http/1.1 200 ok\n";
        // 正文部分的数据类型
        http_response += "Content-Type: text/html; charset=utf8\n";
        http_response += "Content-Length: " + std::to_string(st.st_size) + "\n";//st_size是文件内容大小
        http_response += "\n"; //空行

        //下面是正文内容
        ifstream in(html_file);
        if(!in.is_open())//文件打开失败
        {
            std::string http_response = "http/1.1 404 NOT FOUND\n";
            // 正文部分的数据类型
            http_response += "Content-Type: text/html; charset=utf8\n";
            http_response += "\n";
            http_response += "<html><p>你访问的资源不存在</p></html>";
            send(sock, http_response.c_str(), http_response.size(), 0);
        }
        else
        {   
            string content;
            string line;
            while(getline(in, line))//从输入流in中读取数据到line里
            {
                content += line;
            }
            http_response += content;
            in.close();//关闭输入流
            send(sock, http_response.c_str(), http_response.size(), 0);//作用等同于write
        }
        
    }
    close(sock);
}


int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        cout << "Usage: \n\t" << argv[0] << " port" << endl;
        exit(1);
    }

    int listen_sock = Sock::Socket();
    Sock::Bind(listen_sock, atoi(argv[1]));
    Sock::Listen(listen_sock);
    for (;;)
    {
        int new_sock = Sock::Accept(listen_sock);
        if (new_sock >= 0)
        {
            int *pram = new int(new_sock);
            pthread_t tid;
            pthread_create(&tid, nullptr, HandlerRequest, (void *)pram);
        }
    }
}
